package librarianPanels;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableModel;

import clientGUI.PanelDesign;
import clientGUI.MainGUI;
import java.awt.Rectangle;
import java.awt.Font;

public class InventoryManagementPanel extends PanelDesign {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	static JTable table;
	private JTextField textFieldBookName;
	private JTextField textFieldAuthor;
	private JTextField textFieldCategory;
	private JTextField textFieldDescription;
	private JTextField copyNumTextField;
	private JTextField bookNameTextField;
	private JTextField authorTextField;
	private JTextField categoryTextField;
	private JTextField descriptionTextField;
	private JTextField editionTextField;
	private JTextField printDateTextField;
	private JTextField amountTextField;
	private JTextField locationTextField;
	private JTextField indexTextField;
	private JTextField bidTextField;
	private JCheckBox chckbxPopularBook;
	
	public InventoryManagementPanel() {
		setPreferredSize(new Dimension(644, 462));
		setBorder(new LineBorder(new Color(0, 0, 0), 3, true));
		setBounds(0, 85, 644, 462);
		setLayout(null);
		
		
		JPanel pan1=new JPanel();
		pan1.setLayout(null);
		pan1.setPreferredSize(new Dimension(644, 462));
		pan1.setBounds(0, 85, 644, 462);
		
		JPanel pan2=new JPanel();
		pan2.setLayout(null);
		pan2.setPreferredSize(new Dimension(644, 462));
		pan2.setBounds(0, 85, 644, 462);
		
		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		tabbedPane.setBounds(3, 3, 638, 456);
		tabbedPane.addTab("General", pan1);
		tabbedPane.addTab("Add New Book", pan2);
		
		JPanel panel_1 = new JPanel();
		panel_1.setBounds(54, 48, 530, 265);
		pan2.add(panel_1);
		panel_1.setLayout(null);
		
		JPanel panel_4 = new JPanel();
		panel_4.setBounds(0, 35, 253, 127);
		panel_1.add(panel_4);
		panel_4.setLayout(null);
		
		JLabel lblBookName = new JLabel("Book name:");
		lblBookName.setBounds(0, 3, 85, 16);
		panel_4.add(lblBookName);
		background.setLabelFor(lblBookName);
		lblBookName.setBackground(new Color(0,0,0,0));
		
		bookNameTextField = new JTextField();
		bookNameTextField.setBounds(89, 0, 164, 22);
		panel_4.add(bookNameTextField);
		bookNameTextField.setColumns(10);
		
		JLabel lblAuthor = new JLabel("Author:");
		lblAuthor.setBounds(0, 35, 85, 16);
		panel_4.add(lblAuthor);
		lblAuthor.setBackground(new Color(0,0,0,0));
		
		authorTextField = new JTextField();
		authorTextField.setBounds(89, 35, 164, 22);
		panel_4.add(authorTextField);
		authorTextField.setColumns(10);
		
		JLabel lblCategory = new JLabel("Category:");
		lblCategory.setBounds(0, 70, 85, 16);
		panel_4.add(lblCategory);
		lblCategory.setBackground(new Color(0,0,0,0));
		
		categoryTextField = new JTextField();
		categoryTextField.setBounds(89, 70, 164, 22);
		panel_4.add(categoryTextField);
		categoryTextField.setColumns(10);
		
		JLabel lblAmount = new JLabel("Amount:");
		lblAmount.setBounds(0, 105, 85, 16);
		panel_4.add(lblAmount);
		
		amountTextField = new JTextField();
		amountTextField.setBounds(89, 105, 164, 22);
		panel_4.add(amountTextField);
		amountTextField.setColumns(10);
		
		JPanel panel_2 = new JPanel();
		panel_2.setBounds(269, 0, 265, 127);
		panel_1.add(panel_2);
		panel_2.setLayout(null);
		
		JLabel lblDescription = new JLabel("Description:");
		lblDescription.setBounds(0, 70, 85, 16);
		panel_2.add(lblDescription);
		lblDescription.setBackground(new Color(0,0,0,0));
		
		descriptionTextField = new JTextField();
		descriptionTextField.setBounds(97, 70, 164, 22);
		panel_2.add(descriptionTextField);
		descriptionTextField.setColumns(10);
		
		JLabel lblEdition = new JLabel("Edition:");
		lblEdition.setBounds(0, 3, 91, 16);
		panel_2.add(lblEdition);
		
		editionTextField = new JTextField();
		editionTextField.setBounds(97, 0, 164, 22);
		panel_2.add(editionTextField);
		editionTextField.setColumns(10);
		
		JLabel lblPrintDate = new JLabel("Print Date:");
		lblPrintDate.setBounds(0, 37, 91, 16);
		panel_2.add(lblPrintDate);
		
		printDateTextField = new JTextField();
		printDateTextField.setBounds(97, 35, 164, 22);
		panel_2.add(printDateTextField);
		printDateTextField.setColumns(10);
		
		JLabel lblLocation = new JLabel("Shelf location:");
		lblLocation.setBounds(0, 105, 91, 16);
		panel_2.add(lblLocation);
		
		locationTextField = new JTextField();
		locationTextField.setBounds(97, 105, 164, 22);
		panel_2.add(locationTextField);
		locationTextField.setColumns(10);
		
		JButton addButton = new JButton("Add Title");
		addButton.setBounds(274, 229, 164, 29);
		panel_1.add(addButton);
		
		JPanel panel_3 = new JPanel();
		panel_3.setBounds(56, 185, 417, 22);
		panel_1.add(panel_3);
		panel_3.setLayout(null);
		
		JButton btnBrowseForIndex = new JButton("Browse");
		btnBrowseForIndex.setBounds(310, 0, 85, 22);
		panel_3.add(btnBrowseForIndex);
		
		JLabel lblPdfIndexPath = new JLabel("PDF Index path:");
		lblPdfIndexPath.setBounds(0, 0, 91, 16);
		panel_3.add(lblPdfIndexPath);
		
		indexTextField = new JTextField();
		indexTextField.setBounds(95, 0, 200, 22);
		panel_3.add(indexTextField);
		indexTextField.setColumns(10);
		btnBrowseForIndex.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				JFileChooser chooser = new JFileChooser();
				chooser.removeChoosableFileFilter(chooser.getFileFilter());
				chooser.setFileFilter(new FileFilter() {
					 
				    public String getDescription() {
				        return "PDF Documents (*.pdf)";
				    }
				 
				    public boolean accept(File f) {
				        if (f.isDirectory()) {
				            return true;
				        } else {
				            return f.getName().toLowerCase().endsWith(".pdf");
				        }
				    }
				});
	            int x=chooser.showOpenDialog(null);
	            if(x==chooser.APPROVE_OPTION)
	            {
		            File file = chooser.getSelectedFile();                
		            String filename = file.getName();
		            indexTextField.setText(file.getPath());
	            }
			}
		});
		
		JLabel lblBookId = new JLabel("Book ID:");
		lblBookId.setBounds(0, 3, 85, 16);
		panel_1.add(lblBookId);
		
		bidTextField = new JTextField();
		bidTextField.setBounds(88, 0, 164, 22);
		panel_1.add(bidTextField);
		bidTextField.setColumns(10);
		
		chckbxPopularBook = new JCheckBox("Popular book");
		chckbxPopularBook.setBounds(264, 137, 105, 25);
		panel_1.add(chckbxPopularBook);
		chckbxPopularBook.setContentAreaFilled(false);
		chckbxPopularBook.setBackground(new Color(0,0,0,0));
		
		JButton btnClear = new JButton("Clear ");
		btnClear.setBounds(88, 229, 164, 29);
		panel_1.add(btnClear);
		btnClear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				categoryTextField.setText("");
				descriptionTextField.setText("");
				editionTextField.setText("");
				printDateTextField.setText("");
				copyNumTextField.setText("");
				bookNameTextField.setText("");
				amountTextField.setText("");
				locationTextField.setText("");
				indexTextField.setText("");
				bidTextField.setText("");
				authorTextField.setText("");
				
			}
		});
		addButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String[] msg=new String[13];
				msg[0]="InventoryManagement";
				msg[1]="New Title";
				msg[2]=bookNameTextField.getText();//book name
				msg[3]=authorTextField.getText();//author
				msg[4]=categoryTextField.getText();//category
				msg[5]=descriptionTextField.getText();//description
				msg[6]=editionTextField.getText();//edition
				msg[7]=printDateTextField.getText();//print date
				msg[8]=amountTextField.getText();//amount
				msg[9]=locationTextField.getText();//location
				msg[10]=indexTextField.getText();//index path
				msg[11]=bidTextField.getText();//new bid
				if(chckbxPopularBook.isSelected())
					msg[12]="1";
				else msg[12]="0";
				
				if((msg[11].equals(""))||(msg[10].equals(""))||(msg[2].equals(""))||(msg[3].equals(""))||(msg[4].equals(""))||(msg[5].equals(""))||(msg[6].equals(""))||(msg[7].equals(""))||(msg[8].equals(""))||(msg[9].equals("")))
				{
					JOptionPane.showMessageDialog(new JFrame(),	"ERROR - Please fill out all forms!","Error",JOptionPane.ERROR_MESSAGE);
				}
				else if(!isLegalDate(msg[7]))
				{
					JOptionPane.showMessageDialog(new JFrame(),	"ERROR - Invalid date. Date pattern must be \"yyyy/MM/dd\"","Error",JOptionPane.ERROR_MESSAGE);
				}
				else if(!MainGUI.isNumber(msg[8]))
				{
					JOptionPane.showMessageDialog(new JFrame(),	"ERROR - Invalid amount requested.","Error",JOptionPane.ERROR_MESSAGE);
				}
				else if(!MainGUI.isNumber(msg[6]))
				{
					JOptionPane.showMessageDialog(new JFrame(),	"ERROR - Invalid edition number","Error",JOptionPane.ERROR_MESSAGE);
				}
				else if(!MainGUI.isNumber(msg[11]))
				{
					JOptionPane.showMessageDialog(new JFrame(),	"ERROR - Invalid book ID","Error",JOptionPane.ERROR_MESSAGE);
				}
				else if(!MainGUI.isName(msg[4]))
				{
					JOptionPane.showMessageDialog(new JFrame(),	"ERROR - Invalid category","Error",JOptionPane.ERROR_MESSAGE);
				}
				else if(msg[10].length()<5||!isPdf(msg[10]))
				{
					JOptionPane.showMessageDialog(new JFrame(),	"ERROR - You must choose a valid pdf file!","Error",JOptionPane.ERROR_MESSAGE);
				}
				else 
				{
					int	n = JOptionPane.showConfirmDialog(new JFrame(),	"Are you sure you want to add this title?","An Inane Question",JOptionPane.YES_NO_OPTION);		
					if(n==1)		
						return;	
					MainGUI.OBLClient.handleMessageFromClient(msg);
				}
			}
		});
		add(tabbedPane);
		
		JPanel panel = new JPanel();
		panel.setBounds(25, 46, 584, 60);
		pan1.add(panel);
		panel.setLayout(null);
		
		
		

		
		
		
		
		textFieldBookName = new JTextField();
		textFieldBookName.setBounds(98, 1, 138, 22);
		panel.add(textFieldBookName);
		textFieldBookName.setColumns(10);
		
		final JCheckBox checkBoxBookName = new JCheckBox("Book Name:");
		checkBoxBookName.setBounds(0, 0, 107, 25);
		panel.add(checkBoxBookName);
		checkBoxBookName.setContentAreaFilled(false);
		
		final JCheckBox checkBoxAuthor = new JCheckBox("Author:");
		checkBoxAuthor.setBounds(0, 35, 71, 25);
		panel.add(checkBoxAuthor);
		checkBoxAuthor.setContentAreaFilled(false);
		
		textFieldAuthor = new JTextField();
		textFieldAuthor.setBounds(98, 36, 138, 22);
		panel.add(textFieldAuthor);
		textFieldAuthor.setColumns(10);
		
		final JCheckBox checkBoxCategory = new JCheckBox("Category:");
		checkBoxCategory.setBounds(244, 0, 85, 25);
		panel.add(checkBoxCategory);
		checkBoxCategory.setContentAreaFilled(false);
		
		final JCheckBox chckbxDescription = new JCheckBox("Description:");
		chckbxDescription.setBounds(244, 35, 107, 25);
		panel.add(chckbxDescription);
		chckbxDescription.setContentAreaFilled(false);
		
		textFieldCategory = new JTextField();
		textFieldCategory.setBounds(343, 1, 138, 22);
		panel.add(textFieldCategory);
		textFieldCategory.setColumns(10);
		
		textFieldDescription = new JTextField();
		textFieldDescription.setBounds(343, 36, 138, 22);
		panel.add(textFieldDescription);
		textFieldDescription.setColumns(10);
		
		JButton btnSearch = new JButton("Search");
		btnSearch.setBounds(493, 0, 91, 60);
		panel.add(btnSearch);
		btnSearch.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent arg0) {
				String selection = String.valueOf(checkBoxBookName.isSelected())+String.valueOf(checkBoxAuthor.isSelected())+String.valueOf(checkBoxCategory.isSelected())+String.valueOf(chckbxDescription.isSelected());
				if(!selection.contentEquals("falsefalsefalsefalse"))
				{
					String[] msgToServer=new String[6];
					msgToServer[0]="InventoryManagement";
					msgToServer[1]=selection;
					msgToServer[2]="'%" + textFieldBookName.getText() + "%'"; 
					msgToServer[3]="'%" + textFieldAuthor.getText() + "%'";
					msgToServer[4]="'%" + textFieldCategory.getText() + "%'";
					msgToServer[5]="'%" + textFieldDescription.getText() + "%'";
					
					MainGUI.OBLClient.handleMessageFromClient(msgToServer);
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),	"ERROR - Please select search option!","Error",JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		
		
	   
		
		
		table = new JTable();
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"BookID", "Name", "Author", "Location", "# Of copys", "Edition", "Print date", "Purchase date", "category", "description", "is popular?", "path of index"
			}
		));
		table.getColumnModel().getColumn(0).setResizable(false);
		table.getColumnModel().getColumn(7).setPreferredWidth(95);
		table.getColumnModel().getColumn(11).setPreferredWidth(87);
		table.getTableHeader().setReorderingAllowed(false);
		table.setBounds(50, 133, 900, 231);
		JScrollPane test = new JScrollPane(table);
		test.setVisible(true);
		test.setBounds(25, 118, 584, 255);
		pan1.add(test);
		
		JScrollPane scrollPane = new JScrollPane();
		test.setColumnHeaderView(scrollPane);

		

		JButton btnWatchBookIndex = new JButton("Watch Book Index");
		btnWatchBookIndex.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(table.getSelectedRow()!=-1)
				{
					String[] msgToServer=new String[2];
					msgToServer[0]="WatchIndex";
					msgToServer[1]=table.getModel().getValueAt(table.getSelectedRow(),0).toString();
					MainGUI.OBLClient.handleMessageFromClient(msgToServer);

				}
				else 
				{
					JOptionPane.showMessageDialog(new JFrame(),	"ERROR - Nothing selected!","Error",JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		btnWatchBookIndex.setBounds(35, 386, 144, 27);
		pan1.add(btnWatchBookIndex);
		
		JButton btnAddCopy = new JButton("Add Copy");
		btnAddCopy.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(table.getSelectedRow()!=-1 )
				{
					int n = JOptionPane.showConfirmDialog(new JFrame(),	"Are you sure you want to add new copy?","An Inane Question",JOptionPane.YES_NO_OPTION);		
					if(n==1)		
						return;	
					String[] s=new String[13];
					s[0]="InventoryManagement";
					s[1]="AddCopy";
					s[2]=table.getModel().getValueAt(table.getSelectedRow(),0).toString();//bid
					s[3]=table.getModel().getValueAt(table.getSelectedRow(),1).toString();//name
					s[4]=table.getModel().getValueAt(table.getSelectedRow(),2).toString();//author
					s[5]=table.getModel().getValueAt(table.getSelectedRow(),8).toString();//category
					s[6]=table.getModel().getValueAt(table.getSelectedRow(),9).toString();//description
					s[7]=table.getModel().getValueAt(table.getSelectedRow(),3).toString();//location
					s[8]=table.getModel().getValueAt(table.getSelectedRow(),5).toString();//edition
					s[9]=table.getModel().getValueAt(table.getSelectedRow(),6).toString();//printdate
					s[10]=table.getModel().getValueAt(table.getSelectedRow(),7).toString();//purchasedate
					if(table.getModel().getValueAt(table.getSelectedRow(),10).toString().contentEquals("YES"))//ispop
						s[11]="1";
					else s[11]="0";
					s[12]=table.getModel().getValueAt(table.getSelectedRow(),11).toString();//path index
					MainGUI.OBLClient.handleMessageFromClient(s);
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),	"ERROR - Nothing selected!","Error",JOptionPane.ERROR_MESSAGE);
				}
				
			}
		});
		btnAddCopy.setBounds(191, 386, 122, 27);
		pan1.add(btnAddCopy);
		
		
		
		copyNumTextField = new JTextField();
		copyNumTextField.setBounds(518, 386, 37, 27);
		pan1.add(copyNumTextField);
		copyNumTextField.setColumns(10);
		
		JButton btnRemove = new JButton("Remove Copy Number: ");
		btnRemove.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(table.getSelectedRow()!=-1 && copyNumTextField.getText()!=null  )
				{
					int n = JOptionPane.showConfirmDialog(new JFrame(),	"Are you sure you want to remove this copy?","An Inane Question",JOptionPane.YES_NO_OPTION);		
					if(n==1)		
						return;	
					String[] s=new String[4];
					s[0]="InventoryManagement";
					s[1]="Remove";
					s[2]=copyNumTextField.getText();//copy num
					s[3]=table.getModel().getValueAt(table.getSelectedRow(),0).toString();//bid
					if(s[2].contentEquals(""))
					{
						JOptionPane.showMessageDialog(new JFrame(),	"ERROR - Invalid copy number input!","Error",JOptionPane.ERROR_MESSAGE);
					}
					else if(!MainGUI.isNumber(s[2]))
					{
						JOptionPane.showMessageDialog(new JFrame(),	"ERROR - Invalid copy number input!","Error",JOptionPane.ERROR_MESSAGE);
					}
					else
						MainGUI.OBLClient.handleMessageFromClient(s);
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),	"ERROR - Nothing selected!","Error",JOptionPane.ERROR_MESSAGE);
				}
				
			}
		});
		btnRemove.setBounds(325, 386, 171, 27);
		pan1.add(btnRemove);
		remove(background);
		JLabel lblAddNewTitle = new JLabel("Add new book");
		lblAddNewTitle.setFont(new Font("Tahoma", Font.PLAIN, 29));
		lblAddNewTitle.setBounds(228, 0, 182, 49);
		pan2.add(lblAddNewTitle);
		
		JLabel lblInventoryManagement = new JLabel("Inventory Management");
		lblInventoryManagement.setFont(new Font("Tahoma", Font.PLAIN, 29));
		lblInventoryManagement.setBounds(149, 0, 340, 49);
		pan1.add(lblInventoryManagement);
		JLabel x=new JLabel();
		x.setIcon(background.getIcon());
		x.setBounds(new Rectangle(0, 0, 638, 456));
		JLabel y=new JLabel();
		y.setIcon(background.getIcon());
		y.setBounds(new Rectangle(0, 0, 638, 456));
		pan2.add(x);
		
	
		pan1.add(y);
		add(background);

		
	}
	
	/** gets a matrix representing a table and alters the table in the panel
	 * @param x - a string matrix with the data we want to put in the table
	 */
	public static void changeTableContent(String[][] x)
	{
		for (int i=0;i<x.length;i++)
		{
			if(x[i][10].equals("1"))
				x[i][10]="YES";
			else
				x[i][10]="NO";
		}
		table.setModel(new DefaultTableModel(x,		new String[] {
				"BookID", "Name", "Author", "Location", "# Of copys", "Edition","Print date", "Purchase date", "category", "description","is popular?","path of index"
			}){
			private static final long serialVersionUID = 1L;
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		});
		table.getColumnModel().getColumn(7).setPreferredWidth(95);
		table.getColumnModel().getColumn(11).setPreferredWidth(87);
		table.getTableHeader().setReorderingAllowed(false);
	}
	
	/**checks weather the string is a legal date format of the type yyyy/MM/dd
	 * @param s - date we want to check
	 * @return "true" if the date is legal.
	 * 			"false" if not.
	 */
	boolean isLegalDate(String s) {
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
	    sdf.setLenient(false);
	    return sdf.parse(s, new ParsePosition(0)) != null;
	}
	
	
	/** checks weather a file is .pdf 
	 * @param path - path to the file you want to upload.
	 * @return "true" if the file is pdf
	 * 		   "false" if the file is not pdf
	 */
	boolean isPdf(String path)
	{
		char[] temp=path.toCharArray();
		if((temp[temp.length-4]=='.')&&(temp[temp.length-3]=='p') && (temp[temp.length-2]=='d')&& (temp[temp.length-1]=='f'))
			return true;		
		return false;		
	}
}
